package cn.glutnn.controller;

import cn.glutnn.entity.Address;
import cn.glutnn.entity.Result;
import cn.glutnn.service.AddressService;
import cn.glutnn.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Address)表控制层
 *
 * @author msh
 * @since 2024-10-25 09:18:29
 */
@Tag(name = "地址管理模块")
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @Operation(summary = "添加地址")
    @PostMapping("/add")
    public Result add(@RequestBody Address address, BindingResult bindingResult) {
        //检查项目
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            return new Result<String>(1, "添加失败", s);
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        //判断是否将新添加的地址设为默认
        if (address.getIsDefault() == 1) {
            //先将所有地址的默认字段设置为0
            UpdateWrapper<Address> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("own_name", username);
            updateWrapper.set("is_default", 0);
            addressService.update(updateWrapper);
        }
        address.setOwnName(username);
        addressService.save(address);
        return new Result(0, "添加成功", null);
    }

    //根据登录用户名查询所有地址
    @Operation(summary = "根据登录用户名查询所有地址")
    @GetMapping("/selectByOwnName")
    public Result<List<Address>> selectByOwnName() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("own_name", username);
        List<Address> addresses = addressService.list(wrapper);
        return new Result<List<Address>>(0, "查询成功", addresses);
    }

    @Operation(summary = "根据登录用户名查询默认地址")
    @GetMapping("/selectDefaultByOwnName")
    public Result<Address> selectDefaultByOwnName() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("own_name", username);
        wrapper.eq("is_default", 1);
        Address address = addressService.getOne(wrapper);
        return new Result<Address>(0, "查询成功", address);
    }

    @Operation(summary = "默认地址信息更新操作", description = "修改地址信息，并同时可以设置默认地址，默认地址只能有一个，当你设置一个地址为默认地址时，执行清除当前用户的其他的默认地址")
    @PostMapping("/defaultAddressInfoUpdate")
    public Result<String> clearFieldDefaultAddressInfo(@RequestBody Address address) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        //清除默认地址字段，数据表设置为 0
        UpdateWrapper<Address> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("own_name", username)
                .eq("is_default", 1).
                set("is_default", 0);
        addressService.update(updateWrapper);
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getId, address.getId())
                .set(Address::getIsDefault, 1);
        addressService.update(wrapper);
        return new Result<String>(0, "地址信息更新成功", null);
    }

    @Operation(summary = "删除地址信息")
    @DeleteMapping("/deleteById/{id}")
    public Result<String> deleteById(@PathVariable Integer id) {
        addressService.removeById(id);
        return new Result<String>(0, "删除地址信息成功", null);
    }
}

